// var https = require('https');
// var http = require('http');
var axios = require('axios');
var Qs = require('qs');
var mysql = require('mysql');
var fs = require('fs');
var moment = require('moment');

var util = {
    userAgents:[
        'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.0.12) Gecko/20070731 Ubuntu/dapper-security Firefox/1.5.0.12',
        'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Acoo Browser; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 3.0.04506)',
        'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11',
        'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/535.20 (KHTML, like Gecko) Chrome/19.0.1036.7 Safari/535.20',
        'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.8) Gecko Fedora/1.9.0.8-1.fc10 Kazehakase/0.5.6',
        'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.71 Safari/537.1 LBBROWSER',
        'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0; .NET CLR 3.5.30729; .NET CLR 3.0.30729; .NET CLR 2.0.50727; Media Center PC 6.0) ,Lynx/2.8.5rel.1 libwww-FM/2.14 SSL-MM/1.4.1 GNUTLS/1.2.9',
        'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)',
        'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; QQBrowser/7.0.3698.400)',
        'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E)',
        'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:2.0b13pre) Gecko/20110307 Firefox/4.0b13pre',
        'Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; fr) Presto/2.9.168 Version/11.52',
        'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.0.12) Gecko/20070731 Ubuntu/dapper-security Firefox/1.5.0.12',
        'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; LBBROWSER)',
        'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.8) Gecko Fedora/1.9.0.8-1.fc10 Kazehakase/0.5.6',
        'Mozilla/5.0 (X11; U; Linux; en-US) AppleWebKit/527+ (KHTML, like Gecko, Safari/419.3) Arora/0.6',
        'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; QQBrowser/7.0.3698.400)',
        'Opera/9.25 (Windows NT 5.1; U; en), Lynx/2.8.5rel.1 libwww-FM/2.14 SSL-MM/1.4.1 GNUTLS/1.2.9',
        'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36'
    ],
    ext_json_decode:function($str){
        $str = $str.replace(/'/g,'"');
        $str = $str.replace(/{/g,'{"');
        $str = $str.replace(/:/g,'":');
        $str = $str.replace(/,/g,',"');
        return $str;
    },
    connection:function() {
        return mysql.createConnection({
            host: 'mysql01.uaec.gfox.ltd',
            port:7375,
            user: 'root',
            password: '123qweasd',
            database: 'caiji'
        });
    },
    connectionMDC:function() {
        return mysql.createConnection({
            host: 'localhost',
            port:3306,
            user: 'admin',
            password: 'admin',
            database: 'mdc'
        });
    },
    connection_tradechina:function() {
        return mysql.createConnection({
            host: 'mysql01.uaec.gfox.ltd',
            port:7375,
            user: 'root',
            password: '123qweasd',
            database: 'tradechina'
        });
        // return mysql.createConnection({
        //     host: 'sh-cynosdbmysql-grp-09mo8wr4.sql.tencentcdb.com',
        //     port:26882,
        //     user: 'root',
        //     password: '!@#123qweASD',
        //     database: 'test'
        // });
    },
    credit1688ProductTable:function (connection,tableName) {
        var sql;
        // sql = 'NO_AUTO_VALUE_ON_ZERO;'
        // connection.query(sql);
        // sql = 'SET time_zone = "+00:00";'
        // connection.query(sql);

        sql = 'CREATE TABLE IF NOT EXISTS `'+tableName+'` (`id` int(10) NOT NULL,`title` varchar(300) COLLATE utf8mb4_unicode_ci NOT NULL,`supply` varchar(300) COLLATE utf8mb4_unicode_ci NOT NULL,`fullCategory` varchar(500) COLLATE utf8mb4_unicode_ci NOT NULL,`imgs` text COLLATE utf8mb4_unicode_ci,`videoSrc` varchar(500) COLLATE utf8mb4_unicode_ci NOT NULL,`videoImg` text COLLATE utf8mb4_unicode_ci,`minOrder` varchar(500) COLLATE utf8mb4_unicode_ci NOT NULL,`payments` varchar(500) COLLATE utf8mb4_unicode_ci NOT NULL,`overview` text COLLATE utf8mb4_unicode_ci,`richText` text COLLATE utf8mb4_unicode_ci,`url` text COLLATE utf8mb4_unicode_ci) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;'
        connection.query(sql, function(err, result) {
            if (err) {
                console.log(err);
                console.log('sql err,继续');
                return;
            }
        });
        sql = 'ALTER TABLE `'+tableName+'` ADD UNIQUE KEY `id` (`id`);'
        connection.query(sql, function(err, result) {
            if (err) {
                // console.log('sql err,继续');
            }
        });
        sql = 'ALTER TABLE `'+tableName+'` MODIFY `id` int(10) NOT NULL AUTO_INCREMENT;'
        connection.query(sql, function(err, result) {
            if (err) {
                // console.log('sql err,继续');
            }
        });
    },
    creditSupplyTable:function(connection,tableName) {
        var sql;
        // sql = 'NO_AUTO_VALUE_ON_ZERO;'
        // connection.query(sql);
        // sql = 'SET time_zone = "+00:00";'
        // connection.query(sql);

        sql = 'CREATE TABLE IF NOT EXISTS `'+tableName+'` (`id` int(10) NOT NULL,`companyName` varchar(300) COLLATE utf8mb4_unicode_ci NOT NULL,`fullCategory` varchar(300) COLLATE utf8mb4_unicode_ci NOT NULL,`baseInfo` text COLLATE utf8mb4_unicode_ci,`imgs` text COLLATE utf8mb4_unicode_ci,`otherContent` text COLLATE utf8mb4_unicode_ci,`productsUrl` text COLLATE utf8mb4_unicode_ci,`connectInfo` varchar(1000) COLLATE utf8mb4_unicode_ci DEFAULT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;'
        connection.query(sql, function(err, result) {
            if (err) {
                console.log(err);
                console.log('sql err,继续');
                return;
            }
        });
        sql = 'ALTER TABLE `'+tableName+'` ADD UNIQUE KEY `id` (`id`);'
        connection.query(sql, function(err, result) {
            if (err) {
                console.log('sql err,继续');
            }
        });
        sql = 'ALTER TABLE `'+tableName+'` MODIFY `id` int(10) NOT NULL AUTO_INCREMENT;'
        connection.query(sql, function(err, result) {
            if (err) {
                console.log('sql err,继续');
            }
        });
    },
    creditMdcProductTable:function (connection,tableName) {
        var sql;
        // sql = 'NO_AUTO_VALUE_ON_ZERO;'
        // connection.query(sql);
        // sql = 'SET time_zone = "+00:00";'
        // connection.query(sql);

        sql = 'CREATE TABLE IF NOT EXISTS `'+tableName+'` (`id` int(10) NOT NULL,`productName` varchar(300) COLLATE utf8mb4_unicode_ci NOT NULL,`supplyName` varchar(300) COLLATE utf8mb4_unicode_ci NOT NULL,`fullCategory` varchar(500) COLLATE utf8mb4_unicode_ci NOT NULL,`imgs` text COLLATE utf8mb4_unicode_ci,`videoSrc` varchar(500) COLLATE utf8mb4_unicode_ci NOT NULL,`videoImg` text COLLATE utf8mb4_unicode_ci,`attr` text COLLATE utf8mb4_unicode_ci,`baseInfo` text COLLATE utf8mb4_unicode_ci,`richText` longtext COLLATE utf8mb4_unicode_ci,`url` text COLLATE utf8mb4_unicode_ci) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;'
        connection.query(sql, function(err, result) {
            if (err) {
                console.log(err);
                console.log('sql err,继续');
                return;
            }
        });
        sql = 'ALTER TABLE `'+tableName+'` ADD UNIQUE KEY `id` (`id`);'
        connection.query(sql, function(err, result) {
            if (err) {
                // console.log('sql err,继续');
            }
        });
        sql = 'ALTER TABLE `'+tableName+'` MODIFY `id` int(10) NOT NULL AUTO_INCREMENT;'
        connection.query(sql, function(err, result) {
            if (err) {
                // console.log('sql err,继续');
            }
        });
    },
    creditMdcSupplyTable:function(connection,tableName) {
        var sql;
        // sql = 'NO_AUTO_VALUE_ON_ZERO;'
        // connection.query(sql);
        // sql = 'SET time_zone = "+00:00";'
        // connection.query(sql);

        sql = 'CREATE TABLE IF NOT EXISTS `'+tableName+'` (`id` int(10) NOT NULL,`supplyName` varchar(300) COLLATE utf8mb4_unicode_ci NOT NULL,`fullCategory` varchar(500) COLLATE utf8mb4_unicode_ci NOT NULL,`description` varchar(5000) COLLATE utf8mb4_unicode_ci NOT NULL,`comProfileObj` text COLLATE utf8mb4_unicode_ci,`imgs` text COLLATE utf8mb4_unicode_ci,`connectInfo` text COLLATE utf8mb4_unicode_ci,`logo` varchar(1000) COLLATE utf8mb4_unicode_ci,`tradeCapacit` text COLLATE utf8mb4_unicode_ci,`productionCapacity` text COLLATE utf8mb4_unicode_ci,`productsUrl` text COLLATE utf8mb4_unicode_ci) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;'
        connection.query(sql, function(err, result) {
            if (err) {
                console.log(err);
                console.log('sql err,继续');
                return;
            }
        });
        sql = 'ALTER TABLE `'+tableName+'` ADD UNIQUE KEY `id` (`id`);'
        connection.query(sql, function(err, result) {
            if (err) {
                // console.log('sql err,继续');
            }
        });
        sql = 'ALTER TABLE `'+tableName+'` MODIFY `id` int(10) NOT NULL AUTO_INCREMENT;'
        connection.query(sql, function(err, result) {
            if (err) {
                // console.log('sql err,继续');
            }
        });
    },
    creditTradechinaProductTable:function(connection,tableName) {
        var sql;
        // sql = 'NO_AUTO_VALUE_ON_ZERO;'
        // connection.query(sql);
        // sql = 'SET time_zone = "+00:00";'
        // connection.query(sql);

        sql = 'CREATE TABLE IF NOT EXISTS `'+tableName+'` (`id` int(10) NOT NULL,`title` varchar(400) COLLATE utf8mb4_unicode_ci NOT NULL,`productPrice` longtext COLLATE utf8mb4_unicode_ci,`companyInformation` longtext COLLATE utf8mb4_unicode_ci,`productDetail` longtext COLLATE utf8mb4_unicode_ci,`imgList` longtext COLLATE utf8mb4_unicode_ci,`goodsAttrs` longtext COLLATE utf8mb4_unicode_ci,`categoryList` varchar(500) COLLATE utf8mb4_unicode_ci NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;'
        connection.query(sql, function(err, result) {
            if (err) {
                console.log(err);
                console.log('sql err,继续');
                return;
            }
        });
        sql = 'ALTER TABLE `'+tableName+'` ADD UNIQUE KEY `id` (`id`);'
        connection.query(sql, function(err, result) {
            if (err) {
                // console.log('sql err,继续');
            }
        });
        sql = 'ALTER TABLE `'+tableName+'` MODIFY `id` int(10) NOT NULL AUTO_INCREMENT;'
        connection.query(sql, function(err, result) {
            if (err) {
                // console.log('sql err,继续');
            }
        });
    },
    creditTradechinaSupplyTable:function(connection,tableName) {
        var sql;
        // sql = 'NO_AUTO_VALUE_ON_ZERO;'
        // connection.query(sql);
        // sql = 'SET time_zone = "+00:00";'
        // connection.query(sql);

        sql = 'CREATE TABLE IF NOT EXISTS `'+tableName+'` (`id` int(10) NOT NULL,`title` varchar(400) COLLATE utf8mb4_unicode_ci NOT NULL,`imgList` longtext COLLATE utf8mb4_unicode_ci,`detail` longtext COLLATE utf8mb4_unicode_ci,`baseInfo` longtext COLLATE utf8mb4_unicode_ci,`description` longtext COLLATE utf8mb4_unicode_ci) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;'
        connection.query(sql, function(err, result) {
            if (err) {
                console.log(err);
                console.log('sql err,继续');
                return;
            }
        });
        sql = 'ALTER TABLE `'+tableName+'` ADD UNIQUE KEY `id` (`id`);'
        connection.query(sql, function(err, result) {
            if (err) {
                // console.log('sql err,继续');
            }
        });
        sql = 'ALTER TABLE `'+tableName+'` MODIFY `id` int(10) NOT NULL AUTO_INCREMENT;'
        connection.query(sql, function(err, result) {
            if (err) {
                // console.log('sql err,继续');
            }
        });
    },
    saveErrorList:function (path,data) {
        fs.readFile(path, 'utf8', function(err,result) {
            if(!err && result){
                var jsonData = JSON.parse(result);
                fs.writeFile(path, JSON.stringify(jsonData.contact(data)), function(err) {
                    if (err) {
                        console.log(err);
                    }else{
                        console.log('中止程序前配置文件保存成功');
                        process.exit(0);//主动中止程序
                    }
                });
            }
        })
    },
    insertData:function (connection,tableName,data) {
        var paramsName ='';
        var values ='';
        var addSqlParams = [];
        // console.log('-----------');
        // console.log(data);
        // return false
        for (var i in data){
            // console.log(i);
            paramsName = paramsName +',' + i
            values = values + ',?'

            addSqlParams.push(data[i])
        }
        // return false;
        var addSql = 'INSERT INTO '+tableName+'(id' + paramsName + ') VALUES(0' + values + ')'
        // console.log(addSql);
        // console.log(addSqlParams);
        // return false;
        //增
        connection.query(addSql, addSqlParams, function(err, result) {
            if (err) {
                // console.log('----------------');
                // console.log(addSql);
                console.log(addSqlParams);
                console.log('[INSERT ERROR] - ', err.message);
                // console.log('----------------');
                console.log('')
                console.log('')
                return;
            }
        });
    },
    wait:async function (time) {
        if(time){
            return await new Promise(function (resolve) {
                setTimeout(function () {
                    resolve();
                }, time);
            });
        }
    },
    myRequest:function (url, config){
        var randAgent = parseInt(Math.random()*19);
        let options = Object.assign({
            method: 'get',
            url:url,
            headers: {
                // "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36",
                "User-Agent": util.userAgents[randAgent],
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            transformRequest: [function(data) {
                data = Qs.stringify(data);
                return data;
            }]
        }, config);
        options.proxy = null;

        let promise = new Promise(function(resolve, reject) {
            axios(options).then(function(response) {
                if(response.data){
                    resolve(response.data);
                }else {
                    reject(url+' 无response.data');
                    return false;
                }
            }).catch(function(error) {
                reject(url+' catch异常');
                return false;
            });

            setTimeout(function () {
                reject(url+' 请求超时');
                return false;
            }, 60000);
        });

        return promise;
    },
    eventEmitter: {
        emit: function (eventName,data) {
            var callbackArr = util.events[eventName]
            if (callbackArr && callbackArr.length) {
                for (var i = 0; i < callbackArr.length; i++) {
                    callbackArr[i](data)
                }
            }
        }
    },
    events: {},
    eventListener: {
        on: function (eventName, callback) {
            if (!util.events[eventName]) {
                util.events[eventName] = []
            }
            util.events[eventName].push(callback)
        },
        remove: function (eventName, callback) {
            var callbackArr = util.events[eventName]
            if (callbackArr && callbackArr.length) {
                var index = callbackArr.indexOf(callback);
                callbackArr.splice(index, 1);
            }
        }
    },
    getTime:function () {
        return moment(Date.now()).format('YYYY-MM-DD HH:mm:ss');
    }
}

module.exports = util;
